package com.newgrand.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.newgrand.mapper.*;
import com.newgrand.model.*;
import com.newgrand.utils.DateUtil;
import com.newgrand.utils.HRJdbcTemplate;
import com.newgrand.utils.i8util.EntityConverter;
import com.newgrand.utils.i8util.I8Request;
import com.newgrand.utils.i8util.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: zhanglixin
 * @Data: 2022/9/5 14:52
 * @Description: TODO
 */
@Service
@Slf4j
public class EmpService{

    @Autowired
    private FgOrglistMapper fgOrglistMapper;

    @Autowired
    private HrEpmMainMapper hrEpmMainMapper;

    @Autowired
    private HrEpmBaseMapper hrEpmBaseMapper;

    @Autowired
    private HrEpmLinkMapper hrEpmLinkMapper;

    @Autowired
    private Fg3UserMapper fg3UserMapper;

    @Autowired
    private CPfcBillnoRuleMMapper cPfcBillnoRuleMMapper;

    @Autowired
    private I8Request i8Request;
    @Autowired
    private HRJdbcTemplate jdbcTemplate;
    @Autowired
    private UipLog uipLog;
    @Autowired
    private UIPCommonMapper uipCommonMapper;
    @Autowired
    private EntityConverter entityConverter;

    private static final String epmMstformData ="{\"form\":{\"key\":\"PhId\",\"newRow\":{\"CNo\":\"\",\"CName\":\"\",\"PetName\":\"\",\"ShortName\":\"\",\"SexNo\":\"1\",\"CardType\":\"101\",\"CardNo\":\"\",\"Birthday\":\"\",\"Dept\":\"\",\"CBoo\":\"\",\"Station\":\"\",\"Position\":\"\",\"Pgrand\":\"\",\"Plevel\":\"\",\"CDt\":\"\",\"EmpType\":\"1022\",\"EmpStatus\":\"32\",\"LawTest\":\"\",\"Lawno\":\"\",\"Mobile1\":\"\",\"HomeTell\":\"\",\"Tell2\":\"\",\"Email\":\"\",\"LinkMan\":\"\",\"LinkManMobile\":\"\",\"ProjRolesPhid\":\"\",\"Seq\":\"\",\"DimissDt\":\"\",\"Issecuser\":\"1\",\"SyNetCall\":\"1\",\"IsWeChat\":\"0\",\"FreeShow\":\"1\",\"IsBuyOperator\":\"0\",\"IsOperator\":\"0\",\"Projectmanager\":\"0\",\"BoPoMoFo\":\"\",\"PhId\":\"\",\"Creator\":\"\",\"Editor\":\"\",\"CurOrgId\":\"\",\"NgInsertDt\":\"\",\"NgUpdateDt\":\"\",\"NgRecordVer\":\"\",\"Py\":\"\",\"CompanyMobile\":\"\",\"BasePhId\":\"\",\"LinkPhId\":\"\",\"StationPhId\":\"\",\"BaseNgRecordVer\":\"\",\"LinkNgRecordVer\":\"\",\"StationNgRecordVer\":\"\",\"StationBdt\":\"\",\"PositionGrade\":\"\",\"ImageType\":\"\",\"EmpId\":\"\",\"IsCur\":\"\",\"BillType\":\"\",\"CheckInPhId\":\"\",\"key\":\"\"}}}";


    /**
     * 用于同步数据用
     */
    @Scheduled(cron = "0 0 */12 * * ?")
    public void SyncData(){
        try {
            List<Map<String, Object>> orgList = jdbcTemplate.GetJdbcTemplate().
                    queryForList("select ry.pers_id as \"pers_id\"," +
                            "ry.name as \"name\"," +
                            "ry.sex as \"sex\",dept.id as \"dept_code\"," +
                            "ry.mobile as \"mobile\"," +
                            "ry.perstype as \"perstype\"," +
                            "ry.card_id as \"card_id\"" +
                            " from TUE01_QYWX ry\n" +
                            "left join TUO2_QYWX dept on dept.seq_no=ry.Dept_Code\n" +
                            "where (ry.pers_id is not null or ry.pers_id<>'') and ry.perstype='在职'");
            if(orgList.size()>0){
                int count = orgList.size();
                uipLog.info("empsync", "同步人员","开始同步..");
                for(int i=0;i<count;i++){
                    Map<String,Object> emp = orgList.get(i);
                    EmpModel empModel = new EmpModel();

                    String pers_id = StringHelper.nullToEmpty(emp.get("pers_id"));//职工号
                    String name = StringHelper.nullToEmpty(emp.get("name"));//姓名
                    String sex = StringHelper.nullToEmpty(emp.get("sex"));//勤科 性别
                    String card_id = StringHelper.nullToEmpty(emp.get("card_id"));//勤科 身份证
                    String mobile = StringHelper.nullToEmpty(emp.get("mobile"));//勤科 手机号
                    String perstype = StringHelper.nullToEmpty(emp.get("perstype"));//勤科 员工状态 在职
                    String dept_code = StringHelper.nullToEmpty(emp.get("dept_code"));//勤科 部门

                    List<Map<String, Object>> listOrg =uipCommonMapper.dynamicSql("select phid as \"phid\",parent_orgid as \"parent_orgid\",ocode as \"ocode\" from fg_orglist where user_qkhr='"+dept_code+"'");
                    if (listOrg.size() > 0)
                    {
                        //当前数据存在  就用i8自己的编码
                        String ocode = listOrg.get(0).get("ocode").toString();
                        empModel.dept = ocode;
                    }else{
                        uipLog.error("empsync", "同步人员","pers_id:"+pers_id+",名称:"+name+",部门:"+dept_code+"未找到.");
                        continue;
                    }

                    empModel.cno = pers_id;
                    empModel.cname = name;
                    empModel.mobile = mobile;

                    empModel.cardno = card_id;
                    empModel.sexno = "男".equals(sex)?"1":"2";
                    empModel.empstatus = "在职".equals(perstype)?"32":"35";

                    I8ReturnModel codeMsg = saveEmp(empModel);
                    if(codeMsg.getIsOk()){
                        //处理登录权限问题  只保留当前归属组织的登录权限
                        if (listOrg.size() > 0)
                        {
                            //当前组织phid
                            String parent_orgid = listOrg.get(0).get("parent_orgid").toString();
                            if(!"146220711000003".equals(parent_orgid)){
                                //公司机关下的不处理  001001
                                List<Map<String, Object>> listuserorg =uipCommonMapper.dynamicSql("select phid as \"phid\",userid as \"userid\",orgid as \"orgid\" from fg3_userorg where userid=(select phid from fg3_user where userno='"+empModel.cno+"')");
                                if (listuserorg.size() > 0)
                                {
                                    if(listuserorg.size()==2&&parent_orgid.equals(listuserorg.get(0).get("orgid").toString())){
                                        //还是原组织
                                    }else{
                                        //更换组织了
                                        uipCommonMapper.dynamicSql("update fg3_userorg set orgid='"+parent_orgid+"' where userid='"+listuserorg.get(0).get("userid").toString()+"'");
                                    }
                                }
                            }

                        }
                    }
                    uipLog.info("empsync", "同步人员","pers_id:"+pers_id+",名称:"+name+",同步返回:"+JSON.toJSONString(codeMsg));

                }
                uipLog.info("empsync", "同步人员","结束同步..");
            }
        }catch (Exception ex){
            uipLog.error("empsync", "同步人员","同步异常:"+ex.getMessage());
        }

    }

    public I8ReturnModel saveEmp(EmpModel empModel) {
        I8ReturnModel i8ReturnModel = new I8ReturnModel();
        try {
            //检测是否启用单据编码规则设置  启用了不进行数据同步
            QueryWrapper<CPfcBillnoRuleM> queryCodeRuleWrapper = new QueryWrapper<>();
            queryCodeRuleWrapper.eq("c_btype","EPMMAIN")
                    .eq("codemode","1")
                    .eq("user_mod_flg","1")
                    .eq("sysflg","1");
            Long codeRule = cPfcBillnoRuleMMapper.selectCount(queryCodeRuleWrapper);
            if(codeRule>0){
                i8ReturnModel.setMessage("人员启用了单据编码规则生成,接口不进行同步数据.");
                i8ReturnModel.setIsOk(false);
                i8ReturnModel.setCode("1");
                i8ReturnModel.setErrorCode("E");
                return i8ReturnModel;
            }
            String deptPhid = "";
            String deptOrgPhid = "";
            String dept = empModel.dept;
            if (!StringUtils.isEmpty(dept)) {
                QueryWrapper<FgOrglist> queryDeptIsExistWrapper = new QueryWrapper<>();
                queryDeptIsExistWrapper.eq("ocode",dept);
                List<FgOrglist> rowData = fgOrglistMapper.selectList(queryDeptIsExistWrapper);
                if (rowData.size() == 0) {
                    //部门归属组织未找到
                    i8ReturnModel.setMessage("部门编码: " + dept + " 未找到.");
                    i8ReturnModel.setIsOk(false);
                    i8ReturnModel.setCode("1");
                    i8ReturnModel.setErrorCode("E");
                    return i8ReturnModel;
                } else {
                    deptPhid = rowData.get(0).getPhid();
                    deptOrgPhid = rowData.get(0).getParentOrgid();
                }
            }

            QueryWrapper<HrEpmMain> queryIsExistWrapper = new QueryWrapper<>();
            queryIsExistWrapper.eq("cno",empModel.cno);
            List<HrEpmMain> hrEpmMainList = hrEpmMainMapper.selectList(queryIsExistWrapper);
            Date now = new Date();
            if (hrEpmMainList.size() > 0)
            {//更新
                HrEpmMain hrEpmMain = hrEpmMainList.get(0);
                //更新员工表
                //UpdateWrapper<HrEpmMain> updateEmpWrapper = new UpdateWrapper<>();
                //updateEmpWrapper.set("cname",empModel.cname).setSql("ng_update_dt=to_date('"+DateUtil.dateToString(now,"yyyy-MM-dd HH:mm:ss")+"','yyyy-MM-dd hh24:mi:ss')");
                //updateEmpWrapper.set("sexno",empModel.sexno).
                        //set("cboo",deptOrgPhid).set("dept",deptPhid).
                        //set("cardno",empModel.cardno).set("empstatus",empModel.empstatus).
                        //eq("cno",empModel.cno);
                //hrEpmMainMapper.update(null,updateEmpWrapper);
                uipCommonMapper.dynamicSql("update hr_epm_main set cname='"+empModel.cname+"',sexno='"+empModel.sexno+"',cboo='"+deptOrgPhid+"',dept='"+deptPhid+"',cardno='"+empModel.cardno+"',empstatus='"+empModel.empstatus+"',ng_update_dt=to_date('"+DateUtil.dateToString(now,"yyyy-MM-dd HH:mm:ss")+"','yyyy-MM-dd hh24:mi:ss') where cno='"+empModel.cno+"'");
                //更新联系人表
                //UpdateWrapper<HrEpmLink> updateLinkWrapper = new UpdateWrapper<>();
                //updateLinkWrapper.set("mobile1",empModel.mobile).setSql("ng_update_dt=to_date('"+DateUtil.dateToString(now,"yyyy-MM-dd HH:mm:ss")+"','yyyy-MM-dd hh24:mi:ss')");
                //updateLinkWrapper.set("email",empModel.email).
                        //eq("must_phid",hrEpmMain.getPhid());
                //hrEpmLinkMapper.update(null,updateLinkWrapper);
                uipCommonMapper.dynamicSql("update hr_epm_link set mobile1='"+empModel.mobile+"',ng_update_dt=to_date('"+DateUtil.dateToString(now,"yyyy-MM-dd HH:mm:ss")+"','yyyy-MM-dd hh24:mi:ss') where must_phid='"+hrEpmMain.getPhid()+"'");
                //更新操作员表
                //UpdateWrapper<Fg3User> updateUserWrapper = new UpdateWrapper<>();
                //updateUserWrapper.set("username",empModel.cname).setSql("ng_update_dt=to_date('"+DateUtil.dateToString(now,"yyyy-MM-dd HH:mm:ss")+"','yyyy-MM-dd hh24:mi:ss')");
                //updateUserWrapper.set("email",empModel.email).set("mobileno",empModel.mobile).
                        //set("deptid",deptPhid).
                        //eq("userno",empModel.cno);
                //fg3UserMapper.update(null,updateUserWrapper);
                uipCommonMapper.dynamicSql("update fg3_user set username='"+empModel.cname+"',mobileno='"+empModel.mobile+"',deptid='"+deptPhid+"',ng_update_dt=to_date('"+DateUtil.dateToString(now,"yyyy-MM-dd HH:mm:ss")+"','yyyy-MM-dd hh24:mi:ss')  where userno='"+empModel.cno+"'");
                //更新基础表
                //UpdateWrapper<HrEpmBase> updateBaseWrapper = new UpdateWrapper<>();
                //updateBaseWrapper.setSql("ng_update_dt=to_date('"+DateUtil.dateToString(now,"yyyy-MM-dd HH:mm:ss")+"','yyyy-MM-dd hh24:mi:ss')");
                //updateBaseWrapper.eq("must_phid",hrEpmMain.getPhid());
                //hrEpmBaseMapper.update(null,updateBaseWrapper);


                i8ReturnModel.setMessage("新增成功.");
                i8ReturnModel.setIsOk(true);
                i8ReturnModel.setCode("0");
                i8ReturnModel.setErrorCode("S");
                return i8ReturnModel;

            } else {//新增
                List<NameValuePair> urlParameters = new ArrayList<>();
                HashMap<String, Object> mapInfo = new HashMap<String, Object>();
                mapInfo.put("CNo", empModel.cno);
                mapInfo.put("CName", empModel.cname);
                mapInfo.put("ShortName", "");
                mapInfo.put("EmpStatus", empModel.empstatus);
                mapInfo.put("SexNo", empModel.sexno);
                mapInfo.put("CardType", "101");
                mapInfo.put("CardNo", empModel.cardno);
                mapInfo.put("Dept", deptPhid);
                mapInfo.put("CBoo", deptOrgPhid);
                mapInfo.put("Mobile1", empModel.mobile);
                mapInfo.put("Email", empModel.email);

                urlParameters.add(new BasicNameValuePair("mstformData", entityConverter.SetFieldForm(epmMstformData, mapInfo)));

                urlParameters.add(new BasicNameValuePair("flag", "0"));
                urlParameters.add(new BasicNameValuePair("busguid", ""));
                urlParameters.add(new BasicNameValuePair("id", "-1"));
                urlParameters.add(new BasicNameValuePair("asr_fid", ""));
                urlParameters.add(new BasicNameValuePair("asr_guid", ""));
                urlParameters.add(new BasicNameValuePair("ng3_logid", "0"));
                String i8rv = i8Request.PostFormSync("/HR/Emp/HrEpmMain/save", urlParameters);
                JSONObject i8rvJson = JSON.parseObject(i8rv);
                System.out.println("人员i8返回："+i8rvJson.toString());
                if (i8rvJson != null && i8rvJson.getJSONObject("mainbase").getString("Status").toLowerCase().equals("success")) {

                    //更新操作员表
                    UpdateWrapper<Fg3User> updateUserWrapper = new UpdateWrapper<>();
                    updateUserWrapper.set("mucpwd","0").
                            eq("userno",empModel.cno);
                    fg3UserMapper.update(null,updateUserWrapper);

                    i8ReturnModel.setMessage("新增成功.");
                    i8ReturnModel.setIsOk(true);
                    i8ReturnModel.setCode("0");
                    i8ReturnModel.setErrorCode("S");
                    return i8ReturnModel;
                } else {
                    i8ReturnModel.setMessage("新增失败:"+i8rv);
                    i8ReturnModel.setIsOk(false);
                    i8ReturnModel.setCode("1");
                    i8ReturnModel.setErrorCode("E");
                    return i8ReturnModel;
                }
            }
        }catch (Exception ex){
            i8ReturnModel.setMessage("新增异常:"+ex.getMessage());
            i8ReturnModel.setIsOk(false);
            i8ReturnModel.setCode("1");
            i8ReturnModel.setErrorCode("E");
            return i8ReturnModel;
        }
    }
}
